<?php

namespace App\Http\Controllers\Admin\Rbac;

use App\Http\Controllers\Controller;
use App\Models\Rbac\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $params = $request->only('title','name');
        $res = Menu::query()->whereNull('parent_id')
            ->when($params['name'] ?? null, function ($query, $value) {
                $query->where('name', 'like', '%' . $value . '%');
            })
            ->when($params['title'] ?? null, function ($query, $value) {
                $query->where('title', 'like', '%' . $value . '%');
            })
            ->with('children')->paginate(1000);
        return apiResponse(data: $res);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $params = $request->all();
        $menu = Menu::create($params);
        Permission::firstOrCreate(
            ['name' => $menu->name],
            ['guard_name' => 'admin', 'cn_name' => $menu->title]
        );
        return apiResponse(data: $menu);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $params = $request->all();
        $menu = Menu::query()->findOrFail($id);
        DB::transaction(function () use ($params, $menu){
            // 如果修改了 name，需要同步更新对应的 permission
            if ($menu->name !== $params['name']) {
                Permission::where('name', $menu->name)->delete();
                Permission::firstOrCreate(
                    ['name' => $params['name']],
                    ['guard_name' => 'admin', 'cn_name' => $params['title']]
                );

            }
            $menu->update($params);
        });

        return apiResponse(0,'更新成功',$menu);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $menu = Menu::findOrFail($id);
        Permission::query()->where('name',$menu->name)->delete();
        $menu->delete();
        return apiResponse(msg: '删除成功');
    }
}
